<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class authJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: PUT,GET, POST, OPTIONS,DELETE');
        header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');

        try {
            if (!$user = JWTAuth::toUser(JWTAuth::getToken())){
                return response()->json([
                    'errcode' => 400004,
                    'errmsg' => '无此用户'
                ],400);
            }

        } catch (TokenExpiredException $e) {
            return response()->json([
                'errcode' => 400001,
                'errmsg' => 'token 过期'
            ],400);

        } catch (TokenInvalidException $e) {

            return response()->json([
                'errcode' => 400003,
                'errmsg' => 'token 失效'
            ],400);

        } catch (JWTException $e) {

            return response()->json([
                'errcode' => 400002,
                'errmsg' => 'token 参数错误'
            ],401);
        }
        $input = $request->all(); //操作的内容
        $path = $request->path();  //操作的路由
        $method = $request->method();  //操作的方法
        $ip = $request->ip();  //操作的IP

        $users=JWTAuth::toUser(JWTAuth::getToken());
        $userid = $users->id;  //操作人(要自己获取)
        self::writeLog($userid,$input,$path,$method,$ip);
        return $next($request);
    }
    public  function writeLog($userid,$input,$path,$method,$ip){
        $log = new \App\Models\OperationLog();
        $log->setAttribute('user_id', $userid);
        $log->setAttribute('path', $path);
        $log->setAttribute('method', $method);
        $log->setAttribute('ip', $ip);
        $log->setAttribute('input', json_encode($input, JSON_UNESCAPED_UNICODE));
        $log->save();
    }



}

